package com.turing.post.cardmanagement.impl;

import java.math.BigInteger;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import com.turing.post.cardmanagement.util.CardStock;
import com.turing.post.cardmanagement.util.CardStockDao;
import com.turing.post.cardmanagement.util.SalesGetCardOrder;
import com.turing.post.cardmanagement.util.SalesGetCardOrderBusiness;
import com.turing.post.cardmanagement.util.SalesGetCardOrderDao;
import com.turing.post.cardmanagement.util.SalesGetCardOrderDetail;
import com.turing.post.cardmanagement.util.SalesGetCardOrderDetailDao;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOperLog;
import com.turing.post.common.util.SysOperLogDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.util.PCPSApplicationException;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * 临时领卡\缴回单 业务接口实现
 * 
 * @author kangzhe
 * 
 */
@Stateless(mappedName = "cardmanagement.impl.SalesGetCardOrderBusinessImpl")
@Remote
@Local
public class SalesGetCardOrderBusinessImpl implements SalesGetCardOrderBusiness {

	@EJB(mappedName = "cardmanagement.impl.SalesGetCardOrderDaoImpl")
	private SalesGetCardOrderDao sgcoDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.SalesGetCardOrderDetailDaoImpl")
	private SalesGetCardOrderDetailDao sgcoDetailDaoImpl;

	@EJB(mappedName = "common.impl.PCPSCommonDaoImpl")
	private PCPSCommonDao commonDaoImpl;

	@EJB(mappedName = "common.impl.SysOperLogDaoImpl")
	private SysOperLogDao sysOperLogDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	@EJB(mappedName = "cardmanagement.impl.CardStockDaoImpl")
	private CardStockDao cardStockDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;

	/**
	 * 异常抛出方法
	 * 
	 * @param error
	 * @throws PCPSApplicationException
	 */
	@SuppressWarnings("unused")
	private void errException(String error) throws PCPSApplicationException {
		throw new PCPSApplicationException(
				PCPSApplicationException.ERRCODE_CATEGORY_APPLICATION, "",
				error);
	}

	@Override
	public BigInteger addSalesGetCardOrder(PCPSWebInput input,
			SalesGetCardOrder sgco, List<SalesGetCardOrderDetail> detialList)
			throws PCPSApplicationException {
		/**
		 * 参数合法性检查
		 */
		if (input == null || input.getOperId() == null) {
			errException("登录用户为空!");
		}
		if (sgco == null) {
			errException("临时领卡/缴回实体对象为空!");
		}
		if (detialList == null || detialList.size() <= 0) {
			errException("临时领卡/缴回单明细为空!");
		}
		if (PCPSUtil.isEmpty(sgco.getSaleBranchNo())) {
			errException("销售机构号为空!");
		}
		SysBranch sb = sysBranchDaoImpl.getSysBranchByBranchNo(sgco
				.getSaleBranchNo());
		// 机构不是售卡机构
		if (!sb.getBranchType().equals(SysBranch.SYSBRANCH_SALEBRANCH)) {
			errException("当前登录机构不是销售机构!");
		}
		if (PCPSUtil.isEmpty(sgco.getOrderType())) {
			errException("交易类型为空!");
		}
		if (PCPSUtil.isEmpty(sgco.getName())) {
			errException("经办人姓名为空!");
		}
		IssueCompany issueCompany = issueCompanyDaoImpl
				.getIssueCompanyByIssueCompanyNo(PCPSUtil.getIssueCompanyNo(input));
		if (issueCompany == null) {
			errException("发卡商信息未获取到!");
		}
		/**
		 * 插入临时领卡/缴回单
		 */
		sgco.setSalesGetCardOrderId(commonDaoImpl.getUniqueIntegerKey());
		sgco.setSalesGetCardOrderNo(commonDaoImpl.getOrderNumber(issueCompany
				.getTranDate(), sgco.getSaleBranchNo()));
		sgco.setSaleBranchNo(sgco.getSaleBranchNo());
		sgco.setTranDate(issueCompany.getTranDate());
		sgco.setTranTime(commonDaoImpl.getDatabaseSysTime());
		sgco.setOperId(input.getOperId());
		sgcoDaoImpl.add(sgco);

		/**
		 * 插入临时领卡/缴回单明细,修改卡库存状态
		 */
		SalesGetCardOrderDetail sgcod = null;
		CardStock cs = null;
		String csStatus = "";
		// 领卡
		if (SalesGetCardOrder.SalesGetCardOrder_Type_0.equals(sgco
				.getOrderType())) {
			csStatus = CardStock.CARDSTOCK_STATUS_NORMAL;
		}
		// 在途
		else if (SalesGetCardOrder.SalesGetCardOrder_Type_1.equals(sgco
				.getOrderType())) {
			csStatus = CardStock.CARDSTOCK_STATUS_INTRANSIT;
		}
		CardStock startCs = null;
		CardStock endCs = null;
		BigInteger startSeqNo = null;
		BigInteger endSeqNo = null;
		Map<String, String> countMap = new HashMap<String, String>();
		int allcount = 0;
		for (int i = 0; i < detialList.size(); i++) {
			sgcod = detialList.get(i);
			if (sgcod == null || PCPSUtil.isEmpty(sgcod.getCardStartSeqNo())
					|| PCPSUtil.isEmpty(sgcod.getCardEndSeqNo())) {
				errException("起止卡号不能为空");
			}
			sgcod.setSalesGetCardOrderId(sgco.getSalesGetCardOrderId());
			sgcod.setOrderItemSeqNo(i);

			// 验证号段合法性,如果截取和转化出问题说明号段异常，如果张数不符，也不允许继续
			try {
				startSeqNo = new BigInteger(sgcod.getCardStartSeqNo());
				endSeqNo = new BigInteger(sgcod.getCardEndSeqNo());
				sgcod.setOrderCount(endSeqNo.subtract(startSeqNo).intValue() + 1);
			} catch (Exception e) {
				errException("卡号段" + sgcod.getCardStartSeqNo() + "到"
						+ sgcod.getCardEndSeqNo() + "有误!");
			}
			// 检查首尾批次号是否一致
			startCs = cardStockDaoImpl.getCardStockByCardseqno(sgcod
					.getCardStartSeqNo());
			endCs = cardStockDaoImpl.getCardStockByCardseqno(sgcod
					.getCardEndSeqNo());
			if (startCs == null || endCs == null) {
				errException("起止卡序号的批次号未找到!");
			}
			if (!startCs.getBatchNo().equals(endCs.getBatchNo())) {
				errException("起止卡序号的批次号不一致!");
			}
			sgcod.setBatchNo(startCs.getBatchNo());
			sgcod.setRemark(sgco.getRemark());

			// 将每个明细的count累加用作以后判断卡序号段是否重叠
			allcount = allcount + sgcod.getOrderCount();

			// 判断卡序号段是否连续或状态是否异常
			List<CardStock> cardstocklist = cardStockDaoImpl
					.getCardStockListCountBySysbranchnoNoAndStatusAndCredseqno(
							sgcod.getCardStartSeqNo(), sgcod.getCardEndSeqNo(),
							csStatus, sgco.getSaleBranchNo());
			if (sgcod.getOrderCount() != cardstocklist.size()) {
				HashMap<String, Integer> countMp = cardStockDaoImpl
						.getCardStockCountBySysbranchnoNoAndStatusAndCredseqno(
								sgcod.getCardStartSeqNo(), sgcod
										.getCardEndSeqNo(),
								CardStock.CARDSTOCK_STATUS_NORMAL, sgco
										.getSaleBranchNo());
				if (countMp == null || countMp.size() == 0) {
					errException("该卡号段" + sgcod.getCardStartSeqNo() + "至"
							+ sgcod.getCardEndSeqNo() + "不存在!");
				}
				// 卡状态:正常
				if (SalesGetCardOrder.SalesGetCardOrder_Type_0.equals(sgco
						.getOrderType())) {
					if (countMp.get(CardStock.CARDSTOCK_STATUS_NORMAL) == null) {
						errException("卡序号段:" + sgcod.getCardStartSeqNo() + "至"
								+ sgcod.getCardEndSeqNo() + ",已被领出或已销售!");
					}

				}
				// 卡状态:在途
				if (SalesGetCardOrder.SalesGetCardOrder_Type_1.equals(sgco
						.getOrderType())) {
					if (countMp.get(CardStock.CARDSTOCK_STATUS_INTRANSIT) == null) {
						errException("卡序号段:" + sgcod.getCardStartSeqNo() + "至"
								+ sgcod.getCardEndSeqNo() + ",已被缴回或已销售!");
					}
				}
				if (sgcod.getOrderCount().compareTo(countMp.get(csStatus)) != 0) {
					if (countMp.size() <= 1) {
						errException("卡号段" + sgcod.getCardStartSeqNo() + "至"
								+ sgcod.getCardEndSeqNo() + "不连续!");
					} else {
						errException("卡号段状态异常:"
								+ CardStock.getErrorStatus(countMp));
					}
				}

			}
			for (int k = 0; k < cardstocklist.size(); k++) {
				cs = cardstocklist.get(k);
				countMap.put(cs.getCardSeqNo(), cs.getCardSeqNo());
			}
			if (SalesGetCardOrder.SalesGetCardOrder_Type_0.equals(sgco
					.getOrderType())) {
				cardStockDaoImpl.updateCardStockForSalesGetCardOrder(sgcod
						.getBatchNo(), sgcod.getCardStartSeqNo(), sgcod
						.getCardEndSeqNo(),
						CardStock.CARDSTOCK_STATUS_INTRANSIT, sgco
								.getSalesGetCardOrderId());
			} else if (SalesGetCardOrder.SalesGetCardOrder_Type_1.equals(sgco
					.getOrderType())) {
				cardStockDaoImpl.updateCardStockForSalesGetCardOrder(sgcod
						.getBatchNo(), sgcod.getCardStartSeqNo(), sgcod
						.getCardEndSeqNo(), CardStock.CARDSTOCK_STATUS_NORMAL,
						null);
			}
			// 插入明细
			sgcoDetailDaoImpl.add(sgcod);
		}
		if (countMap.size() != allcount) {
			errException("卡序号段有重叠现象");
		}
		/**
		 * 记录操作日志
		 */
		sysOperLogDaoImpl.insertSysOperLogInfo(input, SysOperLog.operType_Add,
				"添加临时领卡/缴回单", "业务单号：" + sgco.getSalesGetCardOrderNo());

		return sgco.getSalesGetCardOrderId();
	}

	@Override
	public void updateSalesGetCardOrder(PCPSWebInput input,
			SalesGetCardOrder sgco) throws PCPSApplicationException {

	}
}
